package com.xiaobias.distributed.pan.web.messages;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicBoolean;

@Component
@Slf4j
@ServerEndpoint("/websocket/{userId}")
public class MyWebSocketHandler {

    private static Timer timer;
    public final static AtomicBoolean sendStats = new AtomicBoolean(false);
    private static final CopyOnWriteArraySet<MyWebSocketHandler> webSockets = new CopyOnWriteArraySet<>();
    // 用来存在线连接数
    private static final Map<String, Session> sessionPool = new HashMap<>();

    /**
     * 链接成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId) {
        try {
            sessionPool.put(userId, session);
            webSockets.add(this);
            sessionPool.put(userId, session);
            log.debug("websocket消息: 有新的连接，总数为:" + webSockets.size());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }


    /**
     * @param session 连接session
     * @param error   措施信息
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("MyWebSocketServer 连接发生错误");
        error.printStackTrace();
    }


    /**
     * 收到客户端消息后调用的方法
     */
    @OnMessage
    public void onMessage(String message) {
        log.debug("websocket消息: 收到客户端消息:" + message);
    }

    public void sendMessageToClient(String message) {
        // 向客户端发送消息的方法
        log.debug("向客户端发送消息的方法:{}", message);
        try {
            this.sessionPool.get("10086").getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }


    public void scheduleAtFixedRate() {
        timer = new Timer();
        final TimerTask task = new TimerTask() {
            @Override
            public void run() {
                sendStats.set(true);
            }
        };

        timer.scheduleAtFixedRate(task, 1000, 1000);
    }

    public void cancelSchedule() {
        timer.cancel();
    }
}